import 'dart:async';

import 'package:df/page/login/login.dart';
import 'package:df/page/login/login_page.dart';
import 'package:df/page/login/login_response.dart';
import 'package:df/page/router/router.dart';
import 'package:df/page/sms/code_response.dart';
import 'package:df/page/sms/sms_response.dart';
import 'package:df/page/sms/sms.dart';
import 'package:df/service/api_service.dart';
import 'package:df/utils/sp_key.dart';
import 'package:df/widgets/toast_utils.dart';
import 'package:df/utils/logger_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:df/generated/l10n.dart';

///短信登录
class SmsPage extends StatefulWidget {
  @override
  _SmsPageState createState() => _SmsPageState();

  // 正则表达式，用于验证手机号
  static bool isValidPhoneNumber(String phone) {
    bool isValidPhone = false;
    if(phone.isNotEmpty) {
      RegExp regExp = RegExp(r'^[1-9]\d{10}$');
      isValidPhone = regExp.hasMatch(phone);
    }
    return isValidPhone;
  }

  // 取出区号的数字部分
  static String extractNumericPart(String input) {
    RegExp regex = RegExp(r'\d+');
    RegExpMatch? match = regex.firstMatch(input);
    return match?.group(0) ?? '';
  }
}

class _SmsPageState extends State<SmsPage> {
  TextEditingController _phoneController = TextEditingController();
  TextEditingController _codeController = TextEditingController();

  String _phoneNum = "";
  String _appId = "com.ods.digital";
  String _sendTime = "";
  int _countdown = 120;
  bool _isCounting = false;
  // List<String> countryCodes = ['+86', '+852', '+65', '+84', '+855', '+62', '+94'];
  String selectedCountryCode = '+86';


  void _startCountdown() {
    setState(() {
      _countdown = 120;
      _isCounting = true;
    });

    Timer.periodic(Duration(seconds: 1), (Timer timer) {
      setState(() {
        if (_countdown > 0) {
          _countdown--;
        } else {
          _isCounting = false;
          timer.cancel();
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(S.current.smsLogin),
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: () {
            GoRouter.of(context).pop();
          },
        ),
      ),

      body: SafeArea(
        top: true,
        bottom: false,
        left: false,
        right: false,

        child: Padding(
          padding: const EdgeInsets.all(16.0),

          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
          Row(
          children: [

            InkWell(
              onTap: () async {
                // 【1/2】去第二个页面，并把数据带回第一个页面
                final CodeData? result = await GoRouter.of(context).pushNamed(ROUTER_CODE);
                // 检查 result 不为空
                if (result != null) {
                  LogUtils.w("【路由】返回值= ${result.label}, ${result.value}");
                  setState(() {
                    selectedCountryCode = "+${result.value}";
                  });
                } else {
                  LogUtils.e("【路由】返回(空)值");
                }
              },
              child: Row(
                children: [
                  Text(
                    selectedCountryCode,
                    style: TextStyle(fontSize: 16, ),
                  ),
                  Icon(
                    // Icons.arrow_forward_ios,
                    // Icons.arrow_right,
                    Icons.arrow_drop_down,
                    size: 20,
                  ),
                ],
              ),
            ),



            // DropdownButton<String>(
            //   value: selectedCountryCode,
            //   onTap: () async {
            //     if(kDebugMode) {
            //
            //       final CodeData? result = await GoRouter.of(context).pushNamed(ROUTER_CODE);
            //       // 检查 result 不为空
            //       if (result != null) {
            //         LogUtils.w("【路由】返回值= ${result.label}, ${result.value}");
            //       }
            //
            //     }
            //   },
            //   onChanged: (String? value) {
            //     if (value != null) {
            //       setState(() {
            //         selectedCountryCode = value;
            //       });
            //     }
            //   },
            //   items: countryCodes.map<DropdownMenuItem<String>>((String value) {
            //     return DropdownMenuItem<String>(
            //       value: value,
            //       child: Text(value),
            //     );
            //   }).toList(),
            // ),



            SizedBox(width: 8.0),
          // Phone number TextField
          Expanded(
            child: TextField(
              controller: _phoneController,
              keyboardType: TextInputType.phone,
              decoration: InputDecoration(
                labelText: S.current.phoneNumber,
              ),
            ),
          ),
          ],
        ),

              SizedBox(height: 16.0),

              Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: _codeController,
                      keyboardType: TextInputType.number,
                      decoration: InputDecoration(
                        labelText: S.current.verificationCode,
                      ),
                    ),
                  ),
                  SizedBox(width: 16.0),
                  ElevatedButton(
                    onPressed: _isCounting
                        ? null
                        : () {
                      if (SmsPage.isValidPhoneNumber(_phoneController.text)) {
                        _startCountdown();

                        String countryCode = SmsPage.extractNumericPart(selectedCountryCode);
                        _phoneNum = _phoneController.text;

                        // 获取当前 UTC 时间的 DateTime 对象
                        DateTime currentUtcDateTime = DateTime.now().toUtc();
                        // 格式化为 "yyyyMMddHHmmss" 形式的字符串
                        _sendTime = DateFormat('yyyyMMddHHmmss').format(currentUtcDateTime);
                        LogUtils.v("【UTC】时间= ${_sendTime}");

                        String token = Sms.generateToken(_phoneNum, "", _appId, _sendTime);
                        //{data: 短信验证码已发送, resultCode: 0, resultMsg: 成功！, queryCount: 0, resultMsgEx: null}
                        //{data: null, resultCode: 110, resultMsg: 短信发送最小间隔为2分钟.Must wait for 2 minutes to send a new PIN for the same approval., queryCount: 0, resultMsgEx: null}

                        LogUtils.w('【令牌】 ${token}');
                        LogUtils.w('【区号】 ${countryCode}');
                        LogUtils.w('【手机号】 ${_phoneNum}');
                        // 创建 Sms 实例
                        Sms sms = Sms(
                          countryCode: countryCode,
                          phoneNum: _phoneNum,
                          appID: _appId,
                          sendTime: _sendTime,
                          token: token,
                        );

                        Future<SmsResponse> smsResponse = ApiService.postSendCode(sms);
                        smsResponse.then((response) {
                          LogUtils.w("【认证码】结果= ${response.resultMsg}");
                          int code = response.resultCode;
                          LogUtils.w("【认证码】结果= ${code}");
                          if(code == ApiService.kCodeSuccess) {
                            ToastUtils.show(S.current.smsSent);
                          } else {
                            ToastUtils.show(S.current.tryAgainLater);
                          }
                        });
                      } else {
                        ToastUtils.show(S.current.phoneNumberInvalid);
                      }
                    },
                    child: Text(_isCounting ? '$_countdown ${S.current.secondsRepeat}' : S.current.getVerificationCode),
                  ),
                ],
              ),

              SizedBox(height: 32.0),

              ElevatedButton(
                onPressed: () {
                  String countryCode = SmsPage.extractNumericPart(selectedCountryCode);
                  String phoneNum = _phoneController.text;
                  String code = _codeController.text;

                  if(SmsPage.isValidPhoneNumber(phoneNum) && countryCode.isNotEmpty && code.isNotEmpty) {
                    String token = Sms.generateToken(_phoneNum, code, _appId, _sendTime);
                    LogUtils.w('【区号】 ${countryCode}');
                    LogUtils.w('【手机号】 ${phoneNum}');
                    LogUtils.w('【验证码】 ${code}');
                    LogUtils.w('【令牌】 ${token}');
                    // 创建 Sms 实例
                    Login login = Login(
                      loginType: ELoginType.MobilePhone.value,
                      phoneNum: phoneNum,
                      verifyCode: code,
                      appID: _appId,
                      sendTime: _sendTime,
                      token: token,
                    );

                    LoginPage.doLogin(login, context);

                  } else {
                    ToastUtils.show(S.current.fillContentInvalid);
                  }
                  //Fluttertoast.showToast(msg: '【验证码】 ${_codeController.text}');
                },
                child: Text(S.current.login),
              ),
            ],
          ),


        ),
      ),
    );
  }

}
